using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common.Lists;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{
	
	public partial class FormDispatcher : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		
#region Private Members
		
		private int itemId;
		private bool bIsSuperUser = false;
		private bool bIsAdmin = false;
		private Code5Systems.FormMaster.Business.FormInfo _objFormInfo;
		private Code5Systems.FormMaster.Business.FormController _objFormCtl;
		private XmlDocument _objFormXmlDoc;
		
		
#endregion
		
#region  Web Form Designer Generated Code
		
		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}
		
		protected System.Web.UI.WebControls.Menu mnuASPMenu;
		protected System.Web.UI.WebControls.PlaceHolder phMain;
		protected System.Web.UI.WebControls.HyperLink hlHelp;
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();

			var adapters = Context.Request.Browser.Adapters;
			var radioButtonListType = typeof(C5RadioButtonList).AssemblyQualifiedName;
			var rbAdapterType = typeof(C5RadioButtonListAdapter).AssemblyQualifiedName;
			if (!adapters.Contains(radioButtonListType))
			{
				adapters.Add(radioButtonListType, rbAdapterType);
			}

			var checkBoxListType = typeof(C5CheckBoxList).AssemblyQualifiedName;
			var cbListAdapterType = typeof(C5CheckBoxListAdapter).AssemblyQualifiedName;
			if (!adapters.Contains(checkBoxListType))
			{
				adapters.Add(checkBoxListType, cbListAdapterType);
			}

			var checkBoxType = typeof(C5CheckBox).AssemblyQualifiedName;
			var cbAdapterType = typeof(C5CheckBoxAdapter).AssemblyQualifiedName;
			if (!adapters.Contains(checkBoxType))
			{
				adapters.Add(checkBoxType, cbAdapterType);
			}
			
			DotNetNuke.Framework.jQuery.RequestRegistration();
			//DotNetNuke.Framework.jQuery.RequestUIRegistration()
			
			_objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
			_objFormInfo = _objFormCtl.FormInfo;
			
			if (!Page.IsPostBack)
			{
				if (_objFormInfo == null)
				{
					BindNewForm();
					return ;
				}
			}
			
			this.ModuleConfiguration.ModuleTitle = Localization.GetString("ControlTitle_edit", this.LocalResourceFile);
			
			try
			{
				UserController objUsers = new UserController();
				UserInfo objUser = UserController.GetCurrentUserInfo();
				this.trDomainExceeds.Visible = false;
				
				if (objUser.IsSuperUser)
				{
					bIsSuperUser = true;
				}
				
				if (DotNetNuke.Security.PortalSecurity.IsInRole("Administrators"))
				{
					bIsAdmin = true;
				}
				
				if (!Page.IsPostBack)
				{
					BindMenu();
				}
				
				AddScriptVars();
				
				PortalModuleBase objPortalModuleControl = null;
				string strCtl = Request.Params["mctl"];
				
				switch (strCtl)
				{
					case "edit":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormMasterEdit.ascx"));
						objPortalModuleControl.ID = "FormMasterEdit";
						break;
						
					case "head":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormHeadingEdit.ascx"));
						objPortalModuleControl.ID = "FormHeadingEdit";
						break;
						
					case "thanks":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormThankYouEdit.ascx"));
						objPortalModuleControl.ID = "FormThankYouEdit";
						break;
						
					case "auroresp":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormAutoRespMsg.ascx"));
						objPortalModuleControl.ID = "FormAutoRespMsg";
						break;
						
					case "foptions":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormMasterFormOptions.ascx"));
						objPortalModuleControl.ID = "FormMasterFormOptions";
						break;
						
					case "voptions":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormMasterOptions.ascx"));
						objPortalModuleControl.ID = "FormMasterOptions";
						break;
						
					case "files":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormMasterFiles.ascx"));
						objPortalModuleControl.ID = "FormMasterFiles";
						break;
						
					case "report":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormReport.ascx"));
						objPortalModuleControl.ID = "FormReport";
						break;
						
					case "formquery":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormMasterFormQuery.ascx"));
						objPortalModuleControl.ID = "FormMasterFormQuery";
						break;
						
					case "custemp":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormCustomTemplate.ascx"));
						objPortalModuleControl.ID = "FormCustomTemplate";
						break;
						
					case "wsopt":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormDataServiceSettings.ascx"));
						objPortalModuleControl.ID = "FormDataServiceSettings";
						break;
						
					case "dbmgr":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormMasterDBMgr.ascx"));
						objPortalModuleControl.ID = "FormMasterDBMgr";
						break;
						
					case "usrmgr":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormUserManager.ascx"));
						objPortalModuleControl.ID = "FormUserManager";
						break;
						
					case "rules":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormFieldRules.ascx"));
						objPortalModuleControl.ID = "FormFieldRules";
						break;
						
					case "licmgr":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormLicenseMgr.ascx"));
						objPortalModuleControl.ID = "FormLicenseMgr";
						break;
						
					case "about":
						objPortalModuleControl = (PortalModuleBase) (this.LoadControl("FormAbout.ascx"));
						objPortalModuleControl.ID = "FormAbout";
						break;
				}
				
				if (objPortalModuleControl != null)
				{
					objPortalModuleControl.ModuleConfiguration = this.ModuleConfiguration;
					this.phMain.Controls.Add(objPortalModuleControl);
				}
				
			}
			catch (Exception exc)
			{
				Exceptions.ProcessModuleLoadException(this, exc);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
			}
			
		}
		
#endregion
		
		
#region Event Handlers
		
		private void Page_Load(System.Object sender, System.EventArgs e)
		{
			
		}
		
		protected override void AddedControl(System.Web.UI.Control control, int index)
		{
			if (Request.ServerVariables["http_user_agent"].IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) != -1)
			{
				this.Page.ClientTarget = "uplevel";
			}
			base.AddedControl(control, index);
		}
		
		protected void btnCreateForm_Click(System.Object sender, System.EventArgs e)
		{
			
			bool isAjaxPostback = false;
			
			if (DotNetNuke.Framework.AJAX.IsEnabled())
			{
				isAjaxPostback = DotNetNuke.Framework.AJAX.GetScriptManager(this.Page).IsInAsyncPostBack;
			}
			
			if (_objFormInfo == null)
			{
				//Utility.DoLogging(Me.PortalId, Me.ModuleId, "Form does not exist. Using Default", MyBase.ModuleContext)
				//If there is no FormInfo then the module was just added
				//so create a new record in the Database
				_objFormInfo = new Code5Systems.FormMaster.Business.FormInfo();
				_objFormInfo.PortalID = PortalId;
				_objFormInfo.ModuleID = ModuleId;
				_objFormInfo.FormName = "New Form";
				_objFormInfo.FromAddress = this.PortalSettings.Email;
				_objFormInfo.EmailSendAction = (byte) 1;
				_objFormInfo.SaveData = false;
				_objFormInfo.TableColumns = (byte) 1;
				_objFormInfo.TableRows = (byte) 1;
				_objFormInfo.LabelPosition = (byte) 1;
				_objFormInfo.FormDefinition = Localization.GetString("BaseForm", Utility.GetSharedResourceFile());
				_objFormInfo.CreatedByID = this.UserId;
				_objFormInfo.ExtTableForEachPage = false;
				_objFormInfo.CreatedDate = DateTime.Now;
				
				_objFormCtl.Add(_objFormInfo);
				_objFormInfo = _objFormCtl.FormInfo;
				
				//Add the last Report Date Value to the Module Settings
				DotNetNuke.Entities.Modules.ModuleController objModules = new DotNetNuke.Entities.Modules.ModuleController();
				objModules.UpdateModuleSetting(ModuleId, "LastReportDate", DateTime.Now.ToShortDateString());
				
				//Check it External Table Deny List has been Created
				//The Check here is for New instances of the form. There is a Check in the
				//Data Manager but a person could import a form with it's mappings without going
				//to the Data Manager.
				ListController listCtl = new ListController();
				ListInfo oListInfo = listCtl.GetListInfo("FormMasterExtTableMask");
				if (oListInfo == null)
				{
					_objFormCtl.CreateExtTableMaskList(FMGlobals.MaskTables);
				}
				else
				{
					ListEntryInfoCollection list = listCtl.GetListEntryInfoCollection("FormMasterExtTableMask");
					bool bIsNewList = false;
					foreach (ListEntryInfo item in list)
					{
						if (item.Text == "Dashboard_Controls")
						{
							bIsNewList = true;
							break;
						}
					}
					if (!bIsNewList)
					{
						_objFormCtl.CreateExtTableMaskList(FMGlobals.MaskTablesDNN5_2);
					}
					
					bool bIsDNN6ListDone = false;
					foreach (ListEntryInfo item in list)
					{
						if (item.Text == "C5SLLC_FormPage")
						{
							bIsDNN6ListDone = true;
							break;
						}
					}
					if (!bIsDNN6ListDone)
					{
						_objFormCtl.CreateExtTableMaskList(FMGlobals.MaskTablesDNN6);
					}
				}
				
				if (DotNetNuke.Application.DotNetNukeContext.Current.Application.Version.Major > 5)
				{
					string strUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, "", "ctl=Dispatcher", "mid=" + ModuleId);
					if (isAjaxPostback)
					{
						Response.StatusCode = 201;
						Response.AddHeader("Location", strUrl);
					}
					else
					{
						Response.Redirect(strUrl);
					}
				}
				else
				{
					BindMenu();
				}
			}
		}
		
#endregion
		
		
#region DataBind Methods
		
		private void BindMenu()
		{
			string strRole = default(string);
			string strMenuXml = default(string);
			int iRootIndex = default(int);
			int iChildIndex = default(int);
			XmlNodeList oRootNodes = default(XmlNodeList);
			XmlNodeList oChildNodes = default(XmlNodeList);
			string rootMenuID;
			string menuID;
			string menuTitle = default(string);
			string menuUrl = default(string);
			bool bUseFriendlyUrl = false;
			
			this.mnuASPMenu.Visible = true;
			this.phNewForm.Visible = false;
			
			XmlDocument oMenuXmlDoc = new XmlDocument();
			string strFilePath = Server.MapPath(this.ControlPath + "assets/xml/DispatchMenu.xml");
			
			if (!File.Exists(strFilePath))
			{
				
				string rootFolder = Server.MapPath(this.ControlPath + "assets/xml/" + PortalId);
				if (!Directory.Exists(rootFolder))
				{
					Directory.CreateDirectory(rootFolder);
				}
				
				string sourceFile = Server.MapPath(this.ControlPath + "assets/xml/DispatchMenu.xml");
				
				if (File.Exists(sourceFile))
				{
					File.Copy(sourceFile, strFilePath);
				}
				else
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("FileLoad.ErrorMessage", this.LocalResourceFile) + " " + sourceFile, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					return;
				}
			}
			
			MenuItem mRootItem = default(MenuItem);
			MenuItem mChildItem = default(MenuItem);
			Uri extUrl;
			this.mnuASPMenu.Items.Clear();
			
			oMenuXmlDoc.Load(strFilePath);
			strMenuXml = oMenuXmlDoc.OuterXml;
			strMenuXml = strMenuXml.Replace("[MODULEID]", ModuleId.ToString());
			oMenuXmlDoc.LoadXml(strMenuXml);
			
			oRootNodes = oMenuXmlDoc.SelectNodes("//root/menuitem");
			
			for (iRootIndex = 0; iRootIndex <= oRootNodes.Count - 1; iRootIndex++)
			{
				strRole = (string) (oRootNodes[iRootIndex].SelectSingleNode("@Role").Value);
				if (AuthorizeMenuItem(strRole))
				{
					rootMenuID = (string) (oRootNodes[iRootIndex].SelectSingleNode("@id").Value);
					menuTitle = (string) (oRootNodes[iRootIndex].SelectSingleNode("@title").Value);
					menuTitle = Localization.GetString(menuTitle, this.LocalResourceFile);
					if (menuTitle == null)
					{
						menuTitle = (string) (oRootNodes[iRootIndex].SelectSingleNode("@title").Value);
					}
					
					menuUrl = (string) (oRootNodes[iRootIndex].SelectSingleNode("@url").Value);
					if (menuUrl != string.Empty)
					{
						menuUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, "", menuUrl.Split(','));
						//Else
						//    menuUrl = NavigateURL(TabId)
					}
					
					mRootItem = new MenuItem();
					mRootItem.Text = menuTitle;
					mRootItem.NavigateUrl = menuUrl;
					this.mnuASPMenu.Items.Add(mRootItem);
					
					oChildNodes = oRootNodes[iRootIndex].SelectNodes("menuitem");
					for (iChildIndex = 0; iChildIndex <= oChildNodes.Count - 1; iChildIndex++)
					{
						strRole = (string) (oChildNodes[iChildIndex].SelectSingleNode("@Role").Value);
						if (AuthorizeMenuItem(strRole))
						{
							menuID = (string) (oChildNodes[iChildIndex].SelectSingleNode("@id").Value);
							
							menuTitle = (string) (oChildNodes[iChildIndex].SelectSingleNode("@title").Value);
							menuTitle = Localization.GetString(menuTitle, this.LocalResourceFile);
							if (menuTitle == null)
							{
								menuTitle = (string) (oChildNodes[iChildIndex].SelectSingleNode("@title").Value);
							}
							
							menuUrl = (string) (oChildNodes[iChildIndex].SelectSingleNode("@url").Value);
							
							if (menuUrl != string.Empty)
							{
								mChildItem = new MenuItem();
								mChildItem.Text = menuTitle;
								if (Utility.IsValidWebAddress(menuUrl))
								{
									mChildItem.Target = "_blank";
								}
								else
								{
									menuUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, "", menuUrl.Split(','));
								}
								mChildItem.NavigateUrl = menuUrl;
								mRootItem.ChildItems.Add(mChildItem);
							}
							
							
							
						}
					}
				}
			}
			
		}
		
		private void BindNewForm()
		{
			this.btnCreateForm.OnClientClick = "if(confirm(\'" + Localization.GetString("CreateFormMessage", LocalResourceFile) + "\') == false) return ";
			this.mnuASPMenu.Visible = false;
			this.phNewForm.Visible = true;
		}
		
		public void BindAspMenu()
		{
			string strRole = default(string);
			string strMenuXml = default(string);
			int iRootIndex = default(int);
			XmlNodeList oRootNodes = default(XmlNodeList);
			string rootMenuID;
			string menuTitle = default(string);
			string menuUrl = default(string);
			bool bUseFriendlyUrl = false;
			
			XmlDocument oMenuXmlDoc = new XmlDocument();
			string strFilePath = Server.MapPath(this.ControlPath + "assets/xml/DispatchMenu.xml");
			
			if (!File.Exists(strFilePath))
			{
				
				string rootFolder = Server.MapPath(this.ControlPath + "assets/xml/" + PortalId);
				if (!Directory.Exists(rootFolder))
				{
					Directory.CreateDirectory(rootFolder);
				}
				
				string sourceFile = Server.MapPath(this.ControlPath + "assets/xml/DispatchMenu.xml");
				
				if (File.Exists(sourceFile))
				{
					File.Copy(sourceFile, strFilePath);
				}
				else
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("FileLoad.ErrorMessage", this.LocalResourceFile) + " " + sourceFile, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					return;
				}
			}
			
			
			oMenuXmlDoc.Load(strFilePath);
			strMenuXml = oMenuXmlDoc.OuterXml;
			strMenuXml = strMenuXml.Replace("[MODULEID]", ModuleId.ToString());
			oMenuXmlDoc.LoadXml(strMenuXml);
			
			oRootNodes = oMenuXmlDoc.SelectNodes("//root/menuitem");
			
			for (iRootIndex = 0; iRootIndex <= oRootNodes.Count - 1; iRootIndex++)
			{
				strRole = (string) (oRootNodes[iRootIndex].SelectSingleNode("@Role").Value);
				if (AuthorizeMenuItem(strRole))
				{
					rootMenuID = (string) (oRootNodes[iRootIndex].SelectSingleNode("@id").Value);
					menuTitle = (string) (oRootNodes[iRootIndex].SelectSingleNode("@title").Value);
					menuTitle = Localization.GetString(menuTitle, this.LocalResourceFile);
					if (menuTitle == null)
					{
						menuTitle = (string) (oRootNodes[iRootIndex].SelectSingleNode("@title").Value);
					}
					
					menuUrl = (string) (oRootNodes[iRootIndex].SelectSingleNode("@url").Value);
					if (menuUrl != string.Empty)
					{
						menuUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, "", menuUrl.Split(','));
						//Else
						//    menuUrl = NavigateURL(TabId)
					}
				}
			}
			
		}
		
		
#endregion
		
		
#region Helper Methods
		
		private bool AuthorizeMenuItem(string role)
		{
			switch (role)
			{
				case "SU":
					if (this.bIsSuperUser)
					{
						return true;
					}
					break;
				case "Admin":
					if (this.bIsSuperUser || this.bIsAdmin)
					{
						return true;
					}
					break;
				case "All":
					return true;
			}
			
			return false;
			
		}
		
		private void AddScriptVars()
		{
			string scriptVars = default(string);
			scriptVars = string.Format("var appPath = \'{0}\';{1}", Request.ApplicationPath, Environment.NewLine);
			scriptVars += string.Format("var templatePath = \'{0}\';{1}", this.TemplateSourceDirectory, Environment.NewLine);
			Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "C5SLLC_DispatcherAddScriptVars", scriptVars, true);
		}
		
#endregion
		
	}
	
}


